﻿package org.soarsky.wealthchengdu.module.home;

import java.util.ArrayList;
import java.util.List;

import org.soarsky.wealthchengdu.R;
import org.soarsky.wealthchengdu.appliction.MyAppliction;
import org.soarsky.wealthchengdu.cache.AsnsyTaskCache;
import org.soarsky.wealthchengdu.entity.FocusData;
import org.soarsky.wealthchengdu.entity.JsonResult;
import org.soarsky.wealthchengdu.entity.LogonResult;
import org.soarsky.wealthchengdu.entity.WeatherData;
import org.soarsky.wealthchengdu.language.LanguageUtil;
import org.soarsky.wealthchengdu.module.set.SetActivity;
import org.soarsky.wealthchengdu.network.FGFWebService;
import org.soarsky.wealthchengdu.network.ParserResults;
import org.soarsky.wealthchengdu.util.Config;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author 胡伟 主界面
 */
public class HomeActivty extends Activity {
	private ImageView[] imageview; // 小圆点数量
	private GalleryAdapter mGallaryAdapter;
	private ImageView titleChangeView;
	private ImageView titleSetView; // 设置按钮
	private TextView home_tv_weather,// 温度
			home_day,// 日期
			home_week; // 星期
	private GridView home_gridView; // 首页下方gridview
	private Gallery home_img_gallery;
	private LinearLayout home_img_lin;
	private GridView_adapter mAdapter;
	WeatherData dataMsg;
	List<FocusData> focusdata;
	List<String> galleryNumber;
	// gridview假数据
	// int d_img[] = { R.drawable.home_img_park,
	// R.drawable.home_img_city };
	private FGFWebService service;
	private ProgressDialog progressDialog;
	List<String> images;

	private AsyncTask<Void, Void, Boolean> fouceimgTask;
	private AsyncTask<Void, Void, Boolean> weatherTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		initView();
		// getGrid();
		focusdata = new ArrayList<FocusData>();
		mGallaryAdapter = new GalleryAdapter(this);
		home_img_gallery.setAdapter(mGallaryAdapter);

		images = new ArrayList<String>();
		images.add("http://121.199.16.170/data/images/2013/05/242b8a9662480e697d2bdc9fb81c7275.jpg");
		images.add("http://121.199.16.170/data/images/2013/05/242b8a9662480e697d2bdc9fb81c7275.jpg");
		mGallaryAdapter.setList(focusdata);

		service = new ParserResults();
		progressDialog = new ProgressDialog(this);
		//getLogon();
		// 获取网络数据
		loadDatas();
		// 获取新闻
		loadData(); // 获取网络数据
		// 获取新闻

	}

	// // 必须先登录
	// private static void getLogon() {
	// try {
	// JsonResult<LogonResult> jsonResult = service.authLogon("张三");
	// if (jsonResult != null) {
	// if (jsonResult.isError()) {
	// error(jsonResult);
	// } else {// 登录成功
	// System.out.println(jsonResult.getData().getUserId() + "==="
	// + jsonResult.getData().getNickName());
	// }
	// }
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// System.out.println(e.toString() + "===");
	// }
	// }

	// 获取天气
	private void loadData() {
		// progressDialog.setMessage("正在获取新闻列表信息...");
		// progressDialog.show();
		fouceimgTask = new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				 getLogon();
				try {
					// Log.e("ss", "KKKKKKKKKKKKKKKKKKKKKKKKK");
					JsonResult<WeatherData> result = service.getWeather("0");

					if (result == null)
						return false;
					if (result.isError()) {
						error(result);
						// 这里做 数据错误处理
						return false;
					} else {
						dataMsg = result.getData();
						if (dataMsg != null) {
							// Log.e("ss", fdata.get(1).getUrl() +
							// // "wwwwwwwwwwwwwwwwwww");
							// Log.e("ss", dataMsg.getWeather1() +
							// "sssssssssss");
							// Log.e("ss", dataMsg.getWeather2() +
							// "sssssssssss");
							// Log.e("ss", dataMsg.getWeather3() +
							// "sssssssssss");
							// Log.e("ss", dataMsg.getWeather4() +
							// "sssssssssss");
							// Log.e("ss", dataMsg.getWeather5() +
							// "sssssssssss");
							// Log.e("ss", dataMsg.getWeather6() +
							// "sssssssssss");
							// Log.e("ss", dataMsg.getDate_en()
							// + "aaaaaaasssssssssss");
							// Log.e("ss", dataMsg.getWeek_en()
							// + "aaaaaaasssssssssss");
							// Log.e("ss", dataMsg.getFchh()
							// + "aaaaaaasssssssssss");
						}

						return true;
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.i("ss", "12121212121212");
				}
				return false;
			}

			protected void onPostExecute(Boolean result) {
				// UI更新操作
				if (result) {
					// LanguageUtil utils=Config.changeLanguage(0);
					// setText(utils);
					home_tv_weather.setText(dataMsg.getFchh());
					home_day.setText(dataMsg.getDate_y());
					home_week.setText(dataMsg.getWeek());
				} else {

				}
				// progressDialog.dismiss();
			};
		}.execute();

	}

	private void loadDatas() {
		weatherTask = new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				 getLogon();
				try {
					// JsonResult<WeatherData> result = service.getWeather("0");
					focusdata.clear();
					// JsonResult<WeatherData> result = service.getWeather("0");

					// 新闻
					JsonResult<List<FocusData>> focus = service.getFocus("0");

					// 新闻
					if (focus == null) {
						return false;
					}
					if (focus.isError()) {
						error(focus);
						// 这里做 数据错误处理
						return false;
					} else {
						// WeatherData dataMsg = result.getData();
						List<FocusData> fdata = focus.getData();
						if (fdata.size() > 0) {
							for (FocusData data : fdata) {
								focusdata.add(data);
								// Log.e("ss", focusdata.get(1).getUrl()
								// + "aaaaaasw");// 日期
							}
						}
						images.clear();
						for (int i = 0; i < focusdata.size(); i++) {
							images.add(focusdata.get(i).getImg());
							galleryNumber.add(focusdata.get(i).getId());
							// Log.e("ss", focusdata.get(i).getId()
							// + "sssssssssssssssssssssssssssssssss");
						}

						if (fdata != null) {
							// Log.e("ss",
							// focusdata.get(1).getId()+"sssssssssssssssssssssssssssssssss");
							// Log.e("ss", fdata.get(0).getImg()+
							// "wwwwwwwwwwwwwwwwwww");
							// Log.e("ss",
							// focusdata.get(0).getImg()+"wwwwwwwwwwwwwwwwwww");
							// Log.e("ss",
							// focusdata.get(1).getUrl()+"aaaaaasw");//日期

							if (fdata != null) {
								// Log.e("ss", focusdata.get(1).getId()
								// + "sssssssssssssssssssssssssssssssss");
								// Log.e("ss", fdata.get(0).getImg()+
								// "wwwwwwwwwwwwwwwwwww");
								// Log.e("ss",
								// focusdata.get(0).getImg()+"wwwwwwwwwwwwwwwwwww");
								// Log.e("ss",
								// focusdata.get(1).getUrl()+"aaaaaasw");//日期
								// WeatherData werthdata= result.getData();
								// JsonResult<List<FocusData>>
								// focus=service.getFocus("1");
								// String focusdata=focus.getCode();
								// Log.e("ss", focus.getCode()+"swsw");//日期
							}

							return true;
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
				}
				return false;
			}

			protected void onPostExecute(Boolean result) {
				// UI更新操作
				if (result) {
					mGallaryAdapter.setList(focusdata);

					imageview = new ImageView[focusdata.size()];
					AllGalleryShow.getinstanise().setLinerNumber(
							home_img_gallery, HomeActivty.this,
							focusdata.size(), home_img_lin,
							R.drawable.dot_active, R.drawable.dot_ico,
							imageview);// 设置小圆点
					GalleryTaskTimer.starttimer(home_img_gallery, home_img_lin,
							R.drawable.dot_active, R.drawable.dot_ico,
							imageview);// 自动滑动
				} else {

				}
			};
		}.execute();
	}

	// 必须先登录
	private void getLogon() {
		try {
			JsonResult<LogonResult> jsonResult = service.authLogon("张三");
			if (jsonResult != null) {
				if (jsonResult.isError()) {
					error(jsonResult);
				} else {// 登录成功
					System.out.println(jsonResult.getData().getUserId() + "==="
							+ jsonResult.getData().getNickName());

					/**
					 * 昵称，暂时屏蔽！功能未实现
					 */
					// 昵称字段为空，则，设置昵称
					// if (jsonResult.getData().getNickName() == null) {
					// Intent intent = new Intent();
					// intent.setClass(this, SetNickNameDialog.class);
					// startActivity(intent);
					// }
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.toString() + "===");
		}
	}

	private static void error(JsonResult<?> jsonResult) {
		System.out.println("错误码:" + jsonResult.getCode() + "===错误信息:"
				+ jsonResult.getMsg());
	}

	// 初始化控件
	public void initView() {
		galleryNumber = new ArrayList<String>();
		home_tv_weather = (TextView) findViewById(R.id.home_tv_weather);
		home_day = (TextView) findViewById(R.id.home_day);
		home_week = (TextView) findViewById(R.id.home_week);
		home_gridView = (GridView) findViewById(R.id.home_gridView);
		home_img_gallery = (Gallery) findViewById(R.id.home_img_gallery);

		home_img_gallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (galleryNumber.size() > 0) {
					Intent intent = new Intent(HomeActivty.this,
							HomeDetailsActivity.class);
					MyAppliction.ID = galleryNumber.get(arg2
							% galleryNumber.size());
					intent.putExtra("gNumber",
							galleryNumber.get(arg2 % galleryNumber.size()));
					startActivity(intent);
				} else {
					// Intent intent=new
					// Intent(HomeActivty.this,HomeDetailsActivity.class);
					// intent.putExtra("gNumber",galleryNumber.get(arg2));
					// startActivity(intent);
					// Toast.makeText(HomeActivty.this, "正在获取数据中...",
					// 500).show();
				}
				// if (galleryNumber.size() > 0) {
				// Intent intent = new Intent(HomeActivty.this,
				// HomeDetailsActivity.class);
				// intent.putExtra("gNumber", galleryNumber.get(arg2%));
				// startActivity(intent);
				// } else {
				// // Intent intent=new
				// // Intent(HomeActivty.this,HomeDetailsActivity.class);
				// // intent.putExtra("gNumber",galleryNumber.get(arg2));
				// // startActivity(intent);
				// // Toast.makeText(HomeActivty.this, "正在获取数据中...",
				// // 500).show();
				// }

			}
		});

		home_img_lin = (LinearLayout) findViewById(R.id.home_img_lin);
		titleSetView = (ImageView) findViewById(R.id.title_iv_set);
		titleSetView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivty.this, SetActivity.class);
				startActivity(intent);
			}
		});

		mAdapter = new GridView_adapter(HomeActivty.this);
		home_gridView.setAdapter(mAdapter);
		home_gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		titleChangeView = (ImageView) findViewById(R.id.title_ib_c);
		titleChangeView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

//				if (Config.language == Config.LANGUAGE_EN) {
//					MyAppliction.mCn = 0;
//					titleChangeView.setImageResource(R.drawable.title_en);
//				} else {
//					MyAppliction.mCn = 1;
//					titleChangeView.setImageResource(R.drawable.title_china);
//				}
				LanguageUtil util = Config
						.changeLanguage(Config.language == Config.LANGUAGE_EN ? Config.LANGUAGE_ZH
								: Config.LANGUAGE_EN);
				setText(util);
				if(dataMsg != null){
					
				
				if(dataMsg.getDate_y()!=null&&dataMsg.getWeek()!=null&&dataMsg.getDate_en()!=null&&dataMsg.getWeek_en()!=null){
					if (MyAppliction.mCn == 0) {
						home_day.setText(dataMsg.getDate_y());
						home_week.setText(dataMsg.getWeek());
					} else {
						// 这里暂时未返回英文 所以中问代替
						home_day.setText(dataMsg.getDate_en());
						home_week.setText(dataMsg.getWeek_en());
					}
					if (Config.language == Config.LANGUAGE_EN) {
						MyAppliction.mCn = 0;
						titleChangeView.setImageResource(R.drawable.title_en);
					} else {
						MyAppliction.mCn = 1;
						titleChangeView.setImageResource(R.drawable.title_china);
					}
				}else {
					Toast.makeText(HomeActivty.this, "正在获取中英文数据...", 300).show();
				}
				}else {
					Toast.makeText(HomeActivty.this, "正在获取中英文数据...", 300).show();
				}
//				if (MyAppliction.mCn == 0) {
//					home_day.setText(dataMsg.getDate_y());
//					home_week.setText(dataMsg.getWeek());
//				} else {
//					// 这里暂时未返回英文 所以中问代替
//					home_day.setText(dataMsg.getDate_en());
//					home_week.setText(dataMsg.getWeek_en());
//				}
			}
		});
		setText(Config.languageUtil);
	}

	public void setText(LanguageUtil util) {
		// home_day.setText(util.getDate());
		// home_week.setText(util.getWeek());
		mAdapter.setList(getLoadData(util));
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// GalleryTaskTimer.endtimer();
		System.exit(0);
	}

	@Override
	protected void onPause() {
		AsnsyTaskCache.cancelAsyncTask(fouceimgTask);
		AsnsyTaskCache.cancelAsyncTask(weatherTask);
		super.onPause();

	}

	/**
	 * 装载gridview数据
	 * 
	 * @return
	 */
	private List<HomeBean> getLoadData(LanguageUtil util) {
		int images[] = { R.drawable.home_gather_up, R.drawable.home_say_up,
				R.drawable.home_hope_up, R.drawable.home_site_up,
				R.drawable.home_over_up, R.drawable.home_mirror_up,
				R.drawable.home_find_up };
		int imagesdown[] = { R.drawable.home_gather_down,
				R.drawable.home_say_down, R.drawable.home_hope_down,
				R.drawable.home_site_down, R.drawable.home_over_down,
				R.drawable.home_mirror_down, R.drawable.home_find_down };
		// String[] name =
		// getResources().getStringArray(R.array.home_grid_name);
		// String[] context = getResources().getStringArray(
		// R.array.home_grid_context);
		String[] name = util.getHomeGridNames();
		String[] context = util.getHomeGridContexts();
		List<HomeBean> list;
		list = new ArrayList<HomeBean>();
		for (int i = 0; i < images.length; i++) {
			HomeBean home = new HomeBean();
			home.image = images[i];
			home.imagedown = imagesdown[i];
			home.name = name[i];
			home.details = context[i];
			list.add(home);
		}
		return list;
	}

}
